﻿<template>
	<view class="app-container">
		<view class="fixed-header">
			<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

			<!-- 标题导航栏 -->
			<view class="title-navbar" :style="{ height: navbarHeight + 'px' }">
				<!-- 切换按钮容器 -->
				<view class="switch-container">
					分类
				</view>
			</view>

			<!-- 搜索框和类型选择 -->
			<view class="search-container">
				<view class="search-select" v-if="businessType == 1">
					<uni-data-select v-model="selectRangeData" :localdata="range" mode="none"
						:clear="false"></uni-data-select>
				</view>
				<u-search placeholder="输入搜索的关键词" v-model="searchKeyword" :showAction="false" height="40"
					@change="handleSearch"></u-search>
			</view>

			<view class="nav-tabs" v-if="showNavTabs">
				<view v-for="(item, index) in tabs" :key="index"
					:class="['tab-item', currentTab === item.value ? 'active' : '']" @click="changeTab(item.value)">
					{{ item.label }}
				</view>
			</view>

			<!-- 筛选容器 -->
			<view class="filter-container" v-if="showFilterBar">
				<view class="filter-item" @tap="crowdAndThemePopup = true">
					<text class="filter-item-name">人群/主题</text>
					<uni-icons :size="14" color="#999" type="bottom"></uni-icons>
				</view>

				<view class="filter-item" @tap="navToDistrict()">
					<text class="filter-item-name">目的地 </text>
					<uni-icons :size="14" color="#999" type="bottom"></uni-icons>
				</view>

				<view class="filter-item" @tap="navToDaysCalendar()">
					<text class="filter-item-name">天数/日期</text>
					<uni-icons :size="14" color="#999" type="bottom"></uni-icons>
				</view>

				<view class="filter-item">
					<uni-data-select v-model="selectedRecommend" :localdata="recommendRange" mode="none"
						:clear="false"></uni-data-select>
				</view>
			</view>
		</view>

		<!-- 人群/主题弹窗 -->
		<u-popup :show="crowdAndThemePopup" mode="center" @close="crowdAndThemePopup = false"
			@open="crowdAndThemePopup = true" :safeAreaInsetBottom="false" :closeable="true" closeIconPos="top-right">
			<view class="crowdAndThemePopup-content">
				<crowdAndTheme @confirm="confirmCrowdAndTheme"></crowdAndTheme>
			</view>
		</u-popup>

		<!-- 主内容区 -->
		<view class="content-area" :style="contentAreaStyle">
			<view class="category-page">

				<!-- 分类内容区域 -->
				<view class="category-content" v-if="activeCategory">
					<!-- 分类商品列表 - 使用ProductCard组件 -->
					<view class="products-container">
						<view v-for="product in categoryProducts" :key="product.id" class="product-item">
							<product-card :info="product" :show-top-info="false" :show-date-select="true"
								@tap="call(product.mainInfo.productSpu.id)" />
						</view>
					</view>

					<!-- 加载更多 -->
					<view class="load-more" v-if="hasMoreProducts" @click="loadMoreProducts">
						<text>点击加载更多</text>
					</view>
				</view>
			</view>
		</view>
		<global-tab-bar />
	</view>
</template>

<script>
import { updateTabBarSelected } from '@/utils/tabBarUtil';
import GlobalTopNav from '@/components/GlobalTopNav.vue';
import GlobalTabBar from '@/components/GlobalTabBar.vue';
import ProductCard from '@/components/ProductCard.vue';
import crowdAndTheme from '@/pages/merchant/category/crowdAndTheme.vue';
import { request } from '@/utils/request';
import { mergeAllProducts } from '@/utils/productUtil';

export default {
	components: {
		GlobalTopNav,
		GlobalTabBar,
		ProductCard,
		crowdAndTheme
	},
	data() {
		return {
			// 导航栏高度
			statusBarHeight: 0,
			navbarTotalHeight: 0,
			navbarHeight: 0,

			// 公司信息和商家类型
			companyInfo: '',
			businessType: 1,
			initColor: '#0081FF',
			tabs: [],
			currentTab: -1,

			// 搜索关键词
			searchKeyword: '',
			// 搜索防抖定时器
			searchTimer: null,

			// 类型选择范围（一类商家专用）
			range: [
				{ value: "全部类型", text: "全部类型" },
				{ value: "研学接待", text: "研学接待" },
				{ value: "研学团票", text: "研学团票" },
				{ value: "门票零售", text: "门票零售" }
			],
			selectRangeData: "全部类型",

			// 分类列表
			categoryList: [
				{ id: 1, title: '接团', icon: 'list' },
				{ id: 2, title: '资源', icon: 'gift' },
				{ id: 3, title: '合作', icon: 'star' },
				{ id: 4, title: '收藏', icon: 'list' }
			],
			// 当前选中的分类
			activeCategory: null,
			// 商品列表
			categoryProducts: [],
			// 当前页码
			currentPage: 1,
			// 是否还有更多商品
			hasMoreProducts: true,

			// 人群/主题弹窗
			crowdAndThemePopup: false,
			selectedCrowdAndThemeData: null,

			// 推荐排序
			selectedRecommend: '推荐排序',
			recommendRange: [
				{ value: "推荐排序", text: "推荐排序" },
				{ value: "好评优先", text: "好评优先" },
				{ value: "团量优先", text: "团量优先" },
				{ value: "销量优先", text: "销量优先" },
				{ value: "低价优先", text: "低价优先" }
			],
			headerHeights: {
				search: 0,
				navTabs: 0,
				filter: 0
			},
			fixedHeaderHeight: 0
		};
	},
	onLoad(options) {
		console.log('商家端商品管理页面加载');
		console.log('接收到的参数:', options);
		// 初始化导航栏高度
		this.initNavbarHeight();
		// 初始化公司信息
		this.initCompanyInfo();
		// 判断商家类型并模拟从businessSelection跳转的情况
		this.simulateBusinessSelectionEntry();
	},
	onShow() {
		// 设置当前tabBar选中项
		updateTabBarSelected.call(this, 1);

		// 如果没有选中的分类，默认选中第一个
		if (!this.activeCategory && this.categoryList.length > 0) {
			this.activeCategory = this.categoryList[0];
			// 加载分类商品
			this.loadCategoryProducts();
		}
		// 根据最新的公司信息更新导航
		this.initCompanyInfo();
		// 延迟计算高度，确保DOM已渲染
		this.$nextTick(() => {
			setTimeout(() => {
				this.calculateHeaderHeights();
			}, 100);
		});
	},
	onReady() {
		// 页面渲染完成后计算高度
		this.calculateHeaderHeights();
	},
	computed: {
		// 判断是否为三类商家（教培）- 只允许查看，禁止编辑输入框和选择框
		isBusinessType3() {
			return this.companyInfo && this.companyInfo.businessType === 3;
		},

		disableCategorySelection() {
			const businessType = this.companyInfo && this.companyInfo.businessType;
			if (this.isBusinessType3) return true;
			if (this.isApplyCall && businessType === 2) return true;
			return false;
		},

		showNavTabs() {
			return (this.businessType === 2 || this.businessType === 3) && Array.isArray(this.tabs) && this.tabs.length > 0;
		},
		showFilterBar() {
			if (this.businessType === 2) {
				return this.currentTab === 1;
			}
			if (this.businessType === 3) {
				return this.currentTab === 1;
			}
			return false;
		},
		contentAreaStyle() {
			// 优先使用实际测量的 fixedHeaderHeight，如果还没有测量则手动计算
			if (this.fixedHeaderHeight > 0) {
				return {
					paddingTop: this.fixedHeaderHeight + 'px'
				};
			}
			// 如果还没有测量，使用手动计算作为fallback
			let totalHeight = 0;
			// 状态栏高度
			totalHeight += this.statusBarHeight || 0;
			// 导航栏高度
			totalHeight += this.navbarHeight || 0;
			// 搜索容器高度（使用实际测量值，如果没有则使用固定值）
			totalHeight += this.headerHeights.search || 60;
			// 导航标签高度（如果显示，使用实际测量值）
			if (this.showNavTabs) {
				totalHeight += this.headerHeights.navTabs || 45;
			}
			// 筛选容器高度（如果显示，使用实际测量值）
			if (this.showFilterBar) {
				totalHeight += this.headerHeights.filter || 40;
			}
			return {
				paddingTop: totalHeight + 'px'
			};
		}
	},
	watch: {
		businessType(newType, oldType) {
			if (newType !== oldType) {
				this.setInitColor();
				this.initTabs();
			}
		},
		showNavTabs() {
			// 当导航标签显示状态改变时，重新计算高度
			this.$nextTick(() => {
				setTimeout(() => {
					this.calculateHeaderHeights();
				}, 50);
			});
		},
		showFilterBar() {
			// 当筛选栏显示状态改变时，重新计算高度
			this.$nextTick(() => {
				setTimeout(() => {
					this.calculateHeaderHeights();
				}, 50);
			});
		},
		currentTab() {
			// 当切换标签时，筛选栏可能会显示/隐藏，需要重新计算高度
			this.$nextTick(() => {
				setTimeout(() => {
					this.calculateHeaderHeights();
				}, 50);
			});
		}
	},
	methods: {
		/**
		 * 点击商品卡片跳转到对应商品页面
		 */
		call(id) {
			const companyInfo = uni.getStorageSync('companyInfo') || {};
			// 所有商家均进入商品详情页，由详情页根据 businessType 与 mode 决定底栏与后续流转
			uni.navigateTo({ url: `/public/productInfo/productInfo?spuId=${id}&mode=callApply` });
		},
		calculateHeaderHeights() {
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				// 优先获取整个 fixed-header 的高度，这是最准确的方式
				query.select('.fixed-header').boundingClientRect(rect => {
					if (rect && rect.height > 0) {
						this.fixedHeaderHeight = rect.height;
						console.log('✅ 固定头部总高度:', this.fixedHeaderHeight);
					} else {
						console.log('⚠️ fixed-header 未找到或高度为0');
					}
				});
				// 同时测量各个部分的高度（用于调试和fallback）
				query.select('.search-container').boundingClientRect(rect => {
					this.headerHeights.search = rect ? rect.height : 0;
					console.log('✅ 搜索容器高度:', this.headerHeights.search);
				});
				query.select('.nav-tabs').boundingClientRect(rect => {
					this.headerHeights.navTabs = rect ? rect.height : 0;
					console.log('✅ 导航标签高度:', this.headerHeights.navTabs, '显示状态:', this.showNavTabs);
				});
				query.select('.filter-container').boundingClientRect(rect => {
					this.headerHeights.filter = rect && this.showFilterBar ? rect.height : 0;
					console.log('✅ 筛选容器高度:', this.headerHeights.filter, '显示状态:', this.showFilterBar);
				});
				query.exec(() => {
					// 计算总高度
					const calculatedHeight = (this.statusBarHeight || 0) + 
						(this.navbarHeight || 0) + 
						(this.headerHeights.search || 0) + 
						(this.showNavTabs ? (this.headerHeights.navTabs || 0) : 0) + 
						(this.showFilterBar ? (this.headerHeights.filter || 0) : 0);
					console.log('📊 手动计算总高度:', calculatedHeight);
					console.log('📊 状态栏高度:', this.statusBarHeight);
					console.log('📊 导航栏高度:', this.navbarHeight);
					console.log('📊 最终使用的 paddingTop:', this.fixedHeaderHeight > 0 ? this.fixedHeaderHeight : calculatedHeight);
				});
			});
		},
		/**
		 * 处理分类点击
		 */
		handleCategoryClick(category, index) {
			// 如果点击的是当前选中的分类，则不处理
			if (this.activeCategory && this.activeCategory.id === category.id) {
				return;
			}

			// 更新选中的分类
			this.activeCategory = category;
			// 重置页码和商品列表
			this.currentPage = 1;
			this.categoryProducts = [];
			this.hasMoreProducts = true;
			// 加载分类商品
			this.loadCategoryProducts();
		},

		/**
		 * 跳转到创建商品页面
		 */
		navigateToCreateProduct() {
			uni.navigateTo({
				url: '/public/create/index?mode=create'
			});
		},

		/**
		 * 加载分类商品
		 */
		async loadCategoryProducts() {
			// 显示加载动画
			uni.showLoading({
				title: '加载中...'
			});
			// 获取当前用户的公司信息
			const companyInfo = uni.getStorageSync('companyInfo');
			try {
				// 调用实际的API获取产品数据
				const response = await request({
					url: `/product-spu/getByType?merchantType=${companyInfo.businessType}&merchantId=${companyInfo.id}`,
					method: 'GET'
				});

				// 检查响应数据
				if (response.code === 200 && Array.isArray(response.data)) {
					// 🔑 使用productUtil.js处理数据
					// 不传固定的productType，让mergeAllProducts从每个产品数据中自动提取productType
					// 这样可以确保：
					// - B2商家看到的是B1的产品（p1数据，productType=1或3）
					// - B3商家看到的是B2的产品（p2数据，productType=2或4）
					const processedProducts = mergeAllProducts(response.data);

					// 更新商品列表
					if (this.currentPage === 1) {
						this.categoryProducts = processedProducts;
					} else {
						this.categoryProducts = [...this.categoryProducts, ...processedProducts];
					}
					console.log('商品列表:', this.categoryProducts);
					console.log('当前商家类型:', companyInfo.businessType);
					// 判断是否还有更多数据
					this.hasMoreProducts = processedProducts.length === 10;
				} else {
					// 处理API返回错误
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载商品数据失败:', error);
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
			} finally {
				// 隐藏加载动画
				uni.hideLoading();
			}
		},

		/**
		 * 加载更多商品
		 */
		loadMoreProducts() {
			if (!this.hasMoreProducts) {
				return;
			}

			this.currentPage++;
			this.loadCategoryProducts();
		},

		/**
		 * 处理搜索
		 */
		handleSearch() {
			// 防抖处理搜索
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}

			this.searchTimer = setTimeout(() => {
				// 重置页码和商品列表
				this.currentPage = 1;
				this.categoryProducts = [];
				this.hasMoreProducts = true;

				// 加载商品数据
				this.loadCategoryProducts();
			}, 500);
		},

		/**
		 * 初始化导航栏高度
		 */
		initNavbarHeight() {
			// 使用全局注册的navbarUtil方法
			this.statusBarHeight = this.$navbarUtil.getStatusBarHeight();
			this.navbarHeight = this.$navbarUtil.getNavbarHeight();
			this.navbarTotalHeight = this.$navbarUtil.getNavbarTotalHeight();

			console.log('商户页面 - 导航栏高度:', {
				statusBarHeight: this.statusBarHeight,
				navbarHeight: this.navbarHeight,
				navbarTotalHeight: this.navbarTotalHeight
			});
		},

		/**
		 * 初始化公司信息
		 */
		initCompanyInfo() {
			const info = uni.getStorageSync('companyInfo') || {};
			this.companyInfo = info;
			this.businessType = info.businessType || 1;
			console.log('商家信息', this.companyInfo);
			console.log('商家类别', this.businessType);
			this.setInitColor();
			this.initTabs();
		},

		/**
		 * 模拟从businessSelection跳转进入的情况
		 * 判断商家类型（二类或三类），并设置相应的businessEntry
		 */
		simulateBusinessSelectionEntry() {
			const companyInfo = uni.getStorageSync('companyInfo') || {};
			const businessType = companyInfo.businessType || 1;
			console.log('？？？',businessType)
			let businessEntry = ''
			if (businessType === 2) {
				// 二类商家：设置businessEntry为group_travel（组团业务）
				businessEntry = 'group_travel';
				uni.setStorageSync('businessEntry', businessEntry);
			} else if (businessType === 3) {
				// 三类商家：设置businessEntry为third_research（创建研学活动）
				businessEntry = 'third_research';
				uni.setStorageSync('businessEntry', businessEntry);
			}
		},

		setInitColor() {
			if (this.businessType === 1) {
				this.initColor = '#0081FF';
			} else if (this.businessType === 2) {
				this.initColor = '#38B03F';
			} else if (this.businessType === 3) {
				this.initColor = '#F37B1D';
			} else {
				this.initColor = '#0081FF';
			}
		},

		initTabs() {
			if (this.businessType === 1) {
				this.tabs = [];
				this.currentTab = -1;
				return;
			}

			if (this.businessType === 2) {
				this.tabs = [
					{ value: 1, label: '地接/接待' },
					{ value: 2, label: '受邀' },
					{ value: 3, label: '推广' },
					{ value: 4, label: '资源' }
				];
			} else if (this.businessType === 3) {
				this.tabs = [
					{ value: 1, label: '协作广场' },
					{ value: 2, label: '合作受邀' },
					{ value: 3, label: '推广产品' }
				];
			} else {
				this.tabs = [];
				this.currentTab = -1;
				return;
			}

			this.currentTab = this.tabs.length > 0 ? this.tabs[0].value : -1;
		},

		changeTab(val) {
			if (val !== -1) {
				this.currentTab = val
				this.loadCategoryProducts();
				this.calculateHeaderHeights();
			}
		},

		/**
		 * 确认人群/主题选择
		 */
		confirmCrowdAndTheme(data) {
			this.selectedCrowdAndThemeData = data;
			console.log('用户选择的主题数据：', this.selectedCrowdAndThemeData);
			this.crowdAndThemePopup = false;

			// 重新加载商品列表
			this.currentPage = 1;
			this.categoryProducts = [];
			this.hasMoreProducts = true;
			this.loadCategoryProducts();
		},

		/**
		 * 跳转到目的地选择页面
		 */
		navToDistrict() {
			uni.navigateTo({
				url: '/pages/merchant/category/districtSelector'
			});
		},

		/**
		 * 跳转到天数/日期选择页面
		 */
		navToDaysCalendar() {
			uni.navigateTo({
				url: '/pages/merchant/category/daysCalendar'
			});
		}
	}
};
</script>

<style scoped lang="scss">
.app-container {
	display: flex;
	flex-direction: column;
	background: #f5f5f5;
	min-height: 100vh;
}

/* 固定头部样式 */
.fixed-header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: #ffffff;
}

/* 标题导航栏样式 */
.title-navbar {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #ffffff;
}

.switch-container {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

/* 搜索容器样式 */
.search-container {
	height: 60px;
	padding: 0 20rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	gap: 10px;
}

.search-select {
	width: 100px;
}

.search-select ::v-deep .uni-select {
	font-size: 16px;
	color: #333;
}

/* 筛选容器 */
.filter-container {
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 10rpx;
	font-size: 14px;
	padding: 0 20rpx;
	color: #333;
	border-bottom: 1rpx solid #f0f0f0;
}

.filter-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 5rpx;
}

.filter-item-name {
	font-size: 26rpx;
	color: #666;
}

/* 人群/主题弹窗 */
.crowdAndThemePopup-content {
	min-height: 70vh;
	width: 100vw;
	background-color: #fff;
}

/* 内容区域 */
.content-area {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	flex: 1;
}

.category-page {
	padding-bottom: 120rpx;
}

.category-grid {
	background-color: #fff;
	padding: 20rpx 0;
}

.category-item {
	text-align: center;
}

.icon-container {
	width: 80rpx;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 50%;
	margin: 0 auto 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.icon-container.active {
	background-color: #e6f7ff;
}

.grid-text {
	font-size: 24rpx;
	display: block;
	margin-top: 10rpx;
}

/* .category-content 的 margin-top 已移除，避免增加额外空白 */

.products-container {
	background-color: #fff;
}

.product-item {
	padding: 24rpx;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;
}

.product-item:last-child {
	border-bottom: none;
}

.load-more {
	padding: 30rpx 0;
	text-align: center;
	background-color: #fff;
	margin-top: 16rpx;
}

.load-more text {
	color: #999;
	font-size: 26rpx;
}

.empty-tip {
	text-align: center;
	padding: 80rpx 0;
	background-color: #fff;
	margin-top: 16rpx;
}

.empty-icon {
	width: 200rpx;
	height: 200rpx;
	opacity: 0.5;
}

.empty-text {
	display: block;
	color: #999;
	font-size: 28rpx;
	margin-top: 20rpx;
}

/* 顶部导航栏 Tabs */
.nav-tabs {
	display: flex;
	height: 45px;

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		padding: 20rpx 0;
		color: #666;
		transition: all 0.2s;
		position: relative;

	}

	.tab-item.active {
		color: v-bind(initColor);
		font-weight: 600;
		border-bottom: 6rpx solid v-bind(initColor);
	}
}
</style>